package net.esj.auth.view;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import net.esj.auth.pojo.CoreAdmin;
import net.esj.basic.core.view.RequestUtils;
import net.esj.basic.pojo.system.UserRule;
import net.esj.basic.service.provider.UserRuleProvider;
import net.esj.basic.utils.SessionKeyConstants;

public class AuthControlFilter implements Filter {
	
	private String superAdmin;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        CoreAdmin admin = null;
        UserRule rule = UserRuleProvider.getUserRule(CoreAdmin.class);
        if(rule!=null){
        	admin = (CoreAdmin) req.getSession().getAttribute(rule.getSessionKey());
        }
        if(admin==null){
        	resp.sendError(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
            return;
        }
        if(StringUtils.equals(superAdmin,admin.getName())){//配置的超级管理员不受权限控制
        	arg2.doFilter(servletRequest, servletResponse);
        	return;
        }
        String uri =RequestUtils.getURIWithoutSuffixAndContextPath(req);
        if(admin.isAllowed(uri,req.getParameterMap())){
        	if(doCheckOther(admin, req, resp)){
        		arg2.doFilter(servletRequest, servletResponse);
        	}else{
        		resp.sendError(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
        	}
        	return;
        }else{
        	resp.sendError(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
            return;
        }
	}

	/**
	 * 其他条件过滤
	 * @param admin
	 * @param req
	 * @param resp
	 * @return
	 */
	protected boolean doCheckOther(CoreAdmin admin,HttpServletRequest req,HttpServletResponse resp ){
		return true;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		superAdmin = arg0.getInitParameter("SuperAdmin");
	}

}
